package com.design.classroommanagement.activity

import android.os.Bundle
import android.text.TextUtils
import android.widget.*
import com.design.classroommanagement.R
import com.design.classroommanagement.api.ApiManager
import com.design.classroommanagement.api.Role
import com.design.classroommanagement.databinding.ActivityLoginBinding
import com.design.classroommanagement.manager.UserAccountManager
import com.laughing.lib.base.HBaseActivity
import com.laughing.lib.base.HBaseViewModel
import com.laughing.lib.base.getVm
import com.laughing.lib.utils.Logs
import com.laughing.lib.utils.runInBg
import com.laughing.lib.utils.showToast
import com.laughing.lib.utils.startActivity

class LoginActivity : HBaseActivity<HBaseViewModel, ActivityLoginBinding>() {
    private var role: Role = Role.admin
    override fun initCompleted() {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
        if (UserAccountManager.isLogin()) {
            gotoMainPage()
        }
    }

    private fun init() {
        binding.apply {
            rgroup.setOnCheckedChangeListener { radiogroup, i ->
                onSelectTab()
            }
            onSelectTab()
            btnLogin.setOnClickListener {
                login()
            }
            register.setOnClickListener { //为了跳转到注册界面，
                startActivity<RegisterActivity>()
                finish()
            }
        }

    }

    private fun onSelectTab() {
        when (binding.rgroup.checkedRadioButtonId) {
            R.id.admin -> {
                role = Role.admin
            }
            R.id.teacher -> {
                role = Role.teacher
            }
            R.id.student -> {
                role = Role.student
            }
        }

        Logs.d("binding.rgroup.checkedRadioButtonId " + binding.rgroup.checkedRadioButtonId)
        Logs.d("role $role")

    }

    @Throws(Exception::class)
    private fun login() {
        val account = binding.etAccount.text.toString().trim()
        val pwd = binding.etPwd.text.toString().trim()
        if (TextUtils.isEmpty(account)) {
            showToast("请输入账号,账号不能为空")
        } else if (TextUtils.isEmpty(pwd)) {
            showToast("请输入密码,密码不能为空")
        } else {
            runInBg {
                if (ApiManager.login(account, pwd, role) != null) {
                    gotoMainPage()
                } else {
                    showToast("用户名或密码错误")
                }
            }
        }
    }

    private fun gotoMainPage() {
        startActivity<MainActivity>()
        finish()
    }
}